require 'digest/sha1'
class Administrator < ActiveRecord::Base
  validates_presence_of    :password
  
  attr_accessor :newpassword,:newpassword_confirmation
  
  def self.changepassword(administrator)
    logger.info  { "oldpass #{administrator[:password]}"}
    admin=self.authenticate("admin",administrator[:password])
    if admin and administrator[:newpassword]==administrator[:newpassword_confirmation]
      admin.password=(administrator[:newpassword]) 
    else 
      admin=nil      
    end
  
    admin
  end
  
  def validate
    errors.add_to_base("Missing password") if hashed_password.blank?
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password = Administrator.encrypted_password(self.password, self.salt)
  end
  
  def self.authenticate(account, password)
    admin = self.find_by_account(account)
    if admin
      expected_password = encrypted_password(password, admin.salt)
      if admin.hashed_password != expected_password
        admin = nil
      end
    end
    admin
  end
  
  private  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
end
